Writing Programs

Now that we have an idea of the basic types of data and we have seen how they can be receives from users as input, stored in variables, manipulated with operators and statements, and displayed back on screen, we can begin to write programs that actually do useful things. First, however, there is some basic elements to a program that are important to use and important to understand.

Program Header

One of the biggest problems I have in day-to-day web application development is wasting time trying to figure out what the heck this 10-year-old file is and what it does. All of this frustration can be avoided by simply documenting your source code, starting with a program header. Just list the file name, the program name, the original author, creation date, and purpose. If you want to get fancy, you can add rows for modifications and edits. You can copy and paste this header template into the top of all your Python programs. Just remember to fill in the blanks.

# FILE:   # NAME:   # AUTHOR: # DATE:   # PURPOSE:

Example:

# FILE:    tipping.py # NAME:    Tipping Calculator # AUTHOR:  Heather Crites # DATE:    3/5/2017 # PURPOSE: Calculates tips and bill based upon user input

Comments

As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why.

For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments, and they start with the # symbol:

# compute the percentage of the hour that has elapsed percentage = (minute * 100) / 60

In this case, the comment appears on a line by itself. You can also put comments at the end of a line:

percentage = (minute * 100) / 60    # percentage of an hour

Everything from the # to the end of the line is ignored - it has no effect on the execution of the program.

Comments are most useful when they document non-obvious features of the code. It is reasonable to assume that the reader can figure out what the code does; it is more useful to explain why.

This comment is redundant with the code and useless:

v = 5    # assign 5 to v

This comment contains useful information that is not in the code:

v = 5    # velocity in meters/second.

Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a tradeoff.

Use as many useful comments as you can in your program to:

  • explain assumptions
  • explain important decisions
  • explain important details
  • explain problems you're trying to solve
  • explain problems you're trying to overcome in your program, etc

Code tells you how, comments should tell you why.

This is useful for readers of your program so that they can easily understand what the program is doing. Remember, that person can be yourself after six months!

Variables

Unless you like writing unmaintainable code, I suggest that you use descriptive names for most of your variables. 

While naming a variable x is short and sweet, it is pretty meaningless when you are trying to determine whether x is the tip or the tax rate or the user's input.  Better variable names would be tax_rate or TaxRate or varTaxRate.  Find a style you like and stick with it.

Indentation

Whitespace is important in Python. Actually, whitespace at the beginning of the line is important. This is called indentation. Leading whitespace (spaces and tabs) at the beginning of the logical line is used to determine the indentation level of the logical line, which in turn is used to determine the grouping of statements.

This means that statements which go together must have the same indentation. Each such set of statements is called a block. We will see examples of how blocks are important in later chapters.

One thing you should remember is that wrong indentation can give rise to errors. For example:

i = 5 # Error below! Notice a single space at the start of the line   print('Value is', i) print('I repeat, the value is', i)

When you run this, you get the following error:

File "whitespace.py", line 3  print('Value is', i) ^ IndentationError: unexpected indent

Did you notice that there is a single space at the beginning of the second line? The error indicated by Python tells us that the syntax of the program is invalid i.e. the program was not properly written. What this means to you is that you cannot arbitrarily start new blocks of statements (except for the default main block which you have been using all along, of course). Cases where you can use new blocks will be detailed in later lessons such as the control flow.

Use four spaces for indentation. This is the official Python language recommendation. Good editors will automatically do this for you. Make sure you use a consistent number of spaces for indentation, otherwise your program will not run or will have unexpected behavior.

Launch Exercise

Logical and Physical Line

A physical line is what you see when you write the program. A logical line is what Python sees as a single statement. Python implicitly assumes that each physical line corresponds to a logical line.

An example of a logical line is a statement like print('hello world') - if this was on a line by itself (as you see it in an editor), then this also corresponds to a physical line.

Implicitly, Python encourages the use of a single statement per line which makes code more readable.

If you want to specify more than one logical line on a single physical line, then you have to explicitly specify this using a semicolon (;) which indicates the end of a logical line/statement. For example:

i = 5 print(i)

is effectively same as

i = 5; print(i);

which is also same as

i = 5; print(i);

and same as

i = 5; print(i)

However, I strongly recommend that you stick to writing a maximum of a single logical line on each single physical line. The idea is that you should never use the semicolon. In fact, I have never used or even seen a semicolon in a Python program.

There is one kind of situation where this concept is really useful: if you have a long line of code, you can break it into multiple physical lines by using the backslash. This is referred to as explicit line joining:

Code Output
s = 'This is a string. \
This continues the string.'
print(s)

This is a string. This continues the string.

Similarly,

i = \ 5

is the same as

i = 5

Sometimes, there is an implicit assumption where you don't need to use a backslash. This is the case where the logical line has a starting parentheses, starting square brackets or a starting curly braces but not an ending one. This is called implicit line joining. You can see this in action when we write programs using lists in later lessons.

The Programming Process

One of the most difficult hurdles when you are just getting started is how to start a new program or tackle an exercise or lab assignment from the beginning. First, recognize that very few programmers immediately start to write code when they build their programs. They create them in stages. You should to. Here are some simple steps to try:

  • Use pseudocode to design the program: sketch it out or write plain English to describe what you want the program to do. It is often most efficient to do this using comments within the source file itself.
  • Fill in the pseudocode with real code: start using your programming tools to fill in the blanks.
  • Fix any Syntax errors: You learned that syntax errors cause a program to not run at all. Try to run your program, then fix all of these.
  • Test the program repeatedly: use different inputs – negative numbers, letters, floats, and integers. See what sticks and what doesn't work. Fix some of your code if you don't get expected results.

Example:

You need to create a program which can accept a user's name and age, and displays it on the screen.

Step 1: Use pseudocode to design the program

coding example

In this example, I have written my header, then begin to sketch out the program using comments as pseudocode. I kept it simple and in plain terms. I don't need to write a novel.

Step 2: Fill in the pseudocode with real code

coding example

Now I have filled in the blanks with code. For welcoming the user to the program, I used a print statement with a triple quote string. I created two variables to store the keyboard input received from the user for both the name and the age. I then returned the input back to the user with some extra remarks using the print statement.

Step 3: Fix any Syntax errors

coding example

Uh oh! I made a syntax mistake. It says an unexpected indent. This means I have an indentation problem. IDLE has highlighted a space in front of my variable called Name. This space shouldn't be here. I delete the space, correcting my indentation, and now I can run my program without a syntax error.

Step 4: Test

coding example

Now that I fixed my syntax error, my program runs. I put Heather in when prompted for the name and 25 when prompted for the age. Unfortunately, my program stopped running because of a runtime error. It says NameError: name 'name' is not defined. I look at my code and I see my problem. Variable names are case sensitive. I assigned the input received for the user's name to a variable called Name with an uppercase N, but then tried to display a variable called name with a lowercase N. These are two different variables and I never assigned any value to the lowercase version, which is why the error was thrown. I change Name to name and run it again:

coding example

The whole program ran without errors! I run it a few more times and test different values until I am satisfied that it runs the way it is supposed to.

This is a very simple example, but it shows the common steps used.

Launch Exercise

Launch Exercise

Putting it All Together

  • Use a program header
  • Use comments
  • Name your variables well
  • Use appropriate indentation (4 spaces is best)
  • Understand the difference between a physical line and a logical line
  • Create your programs in stages